# -*- coding:utf-8 -*-
# @Time :2021/11/10 20:15
# @Author : Martin
import datetime as datetime
import logging
import os
import sys
from datetime import datetime

import allure
import pytest

root_path = os.path.abspath(__file__)
root_path = '/'.join(root_path.split('/')[:-1])
sys.path.append(root_path)

from web_keys.base_driver import BaseDriver

driver = None


# 通过命令行定义浏览器类型
def pytest_addoption(parser):
    parser.addoption("--browser",
                     action="store",
                     dest="browser",
                     default='chrome',
                     choices=['chrome', 'chrome-debug', 'firefox', 'ie', 'chrome-headless', 'firefox',
                              'firefox-headless', 'chrome-grid'],
                     help="定义运行的浏览器，包括chrome、firefox和ie")


# 初始化日志生成器
@pytest.fixture(scope="session", autouse=True)
def init_logger(request):
    # case_id = getattr(request.node, 'nodeid')
    # case_name = case_id.split('::')[-1]
    # log_path = os.path.join(request.config.rootdir, 'logs', f'{case_name}.log')
    # request.config.pluginmanager.get_plugin("logging-plugin").set_log_path(log_path)
    return logging.getLogger(__name__)


# 设置测试session级前置和后置,获取webdriver session
@pytest.fixture(scope="session")
def init_driver(request, init_logger):
    init_logger.info("打开浏览器")
    browser = request.config.getoption("browser")
    global driver
    driver = BaseDriver(browser).driver
    yield driver
    # 退出浏览器
    if browser != "chrome-debug":
        driver.quit()
        init_logger.info("退出浏览器")



# 设置用例级别前置和后置
@pytest.fixture(autouse=True)
def case_set(request, init_logger):
    case_id = getattr(request.node, 'nodeid')
    init_logger.info(f"开始执行用例{case_id}")
    yield
    init_logger.info(f"结束执行用例{case_id}")


# 配置log文件名称
def pytest_configure(config):
    time_now = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
    config.option.log_file = os.path.join(config.rootdir, 'temp/logs', f'{time_now}.log')


@pytest.mark.hookwrapper(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    """
    用于向测试用例中添加用例的开始时间、内部注释，和失败截图等.
    :param call:用例调用过程
    :param item:测试用例对象
    """
    outcome = yield
    report = outcome.get_result()

    if report.when == 'call' or report.when == "setup":
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            if driver:
                with allure.step("添加失败截图。。。"):
                    allure.attach(driver.get_screenshot_as_png(),
                                  "失败截图", allure.attachment_type.PNG)


